package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.constant.EsNormalConstant;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.detailtab.dto.DetailTabDataGetDTO;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.DistributorAccountEntity;
import com.xbongbong.saas.domain.entity.DistributorAreaEntity;
import com.xbongbong.saas.domain.entity.PromotionProductEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.BusinessDetailButtonEnum;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.WorkFlowEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.enums.business.FullDiscountCouponEnum;
import com.xbongbong.saas.enums.business.MarketingActivityManagementEnum;
import com.xbongbong.saas.enums.business.MarketingBaseEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.SpecialGoodsEnum;
import com.xbongbong.saas.enums.dictionary.ApplicableObjectTypeEnum;
import com.xbongbong.saas.enums.dictionary.InapplicableProductTypeEnum;
import com.xbongbong.saas.enums.dictionary.MarketingStatusEnum;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.DistributorAccountModel;
import com.xbongbong.saas.model.DistributorAreaModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.PromotionActivityModel;
import com.xbongbong.saas.model.PromotionProductModel;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xbongbong.paas.elasticsearch.constant.EsNormalConstant.MINI_MUM_SHOULD_MATCH;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author jyh
 * @version v1.0
 * @since v1.0
 */
@Component
public class MarketingHelp {

    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private DistributorAreaModel distributorAreaModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private UserModel userModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PromotionActivityModel promotionActivityModel;
    @Resource
    private PromotionProductModel promotionProductModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    PaasEsModel paasEsModel;
    @Resource
    private DistributorAccountModel distributorAccountModel;
    @Resource
    private ProductService productService;

    private static final List<Integer> PRIORITY_LEVEL = new ArrayList<>();

    static {
        for (int i = 1; i <= 50; i++) {
            PRIORITY_LEVEL.add(i);
        }
    }

    @Resource
    private IndexTypeModel indexTypeModel;


    /**
     * 获取经销商级别
     */
    public List<ItemPoJo> getDistributorLevel (String corpid) throws XbbException {
        PaasFormExplainEntity distributorExplainList = paasFormExplainModel.getByBusinessType4Distributor(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), corpid, 1);
        List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(distributorExplainList.getExplains(), FieldAttrEntity.class);
        List<ItemPoJo> distributorLevel = new ArrayList<>();
        for (FieldAttrEntity entity : fieldAttrEntityList) {
            if (Objects.equals(entity.getAttr(), DistributorEnum.SCALE.getAttr())) {
                distributorLevel = entity.getItems();
                break;
            }
        }
        return distributorLevel;
    }

    /**
     * 获取促销活动没有在上架或者待上架状态中的优先级
     */
    public List<Integer> getPriorityLevel (String corpid, Integer businessType) throws XbbException {
        List<Integer> disabledPriority = promotionActivityModel.getDisabledPriority(corpid, businessType);
        List<Integer> priorityList = PRIORITY_LEVEL.stream().filter(item -> !disabledPriority.contains(item)).collect(Collectors.toList());
        return priorityList;
    }


    /**
     * 校验新建权限
     */
    public boolean verifyAddPermission(UserVO userVO, Integer businessType){
        Set<String> permSet = userVO.getPermSet();
        if (Objects.equals(businessType, XbbRefTypeEnum.MARKETING_ACTIVITY.getCode()) && !permSet.contains(ProPermissionAliasEnum.MARKETING_ACTIVITY_NEW_ADD.getAlias())) {
            return false;
        }else if (Objects.equals(businessType, XbbRefTypeEnum.PROMOTION_ACTIVITY.getCode())){

        }
        return true;
    }


    /**
     * 详情页展示
     * @param businessType
     * @param tabPojoList
     * @param
     * @param loginUser
     * @param data
     */
    public void handelDetailTab(Integer businessType, List<DetailTabPojo> tabPojoList, PlatFormEnum platFormEnum, UserVO loginUser, JSONObject data, String corpid) {
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(businessType, corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        if (Objects.isNull(paasFormEntityExt)) {
            paasFormEntityExt = new PaasFormEntityExt();
        }
        Long formId = paasFormEntityExt.getId();
        List<BusinessDetailTabEnum> tabEnumList;
        if (Objects.equals(platFormEnum, PlatFormEnum.WEB)) {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermission(businessType, loginUser.getPermSet());
        }else {
            tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, loginUser.getPermSet());
        }
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);

        switch (redundantTemplateTypeEnum){
            case FULL_DISCOUNT_COUPON:
                String applicableObjectType = data.getString(FullDiscountCouponEnum.APPLICABLE_OBJECT_TYPE.getAttr());
                String forbidProductType = data.getString(FullDiscountCouponEnum.INAPPLICABLE_PRODUCT_TYPE.getAttr());
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (Objects.equals(tabEnum, BusinessDetailTabEnum.MARKETING_ACTIVITY_APPLICABLE_OBJECTS) &&!Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode())) {
                        continue;
                    }else if (Objects.equals(tabEnum, BusinessDetailTabEnum.MARKETING_ACTIVITY_INAPPLICABLE_GOODS) &&!Objects.equals(forbidProductType, InapplicableProductTypeEnum.FIXED_PRODUCT.getCode())) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    detailTabPojo.setFormId(formId);
                    tabPojoList.add(detailTabPojo);
                }
                break;
            case SPECIAL_GOODS:
                String promotionApplicableObjectType = data.getString(SpecialGoodsEnum.APPLICABLE_OBJECT_TYPE.getAttr());
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    if (Objects.equals(tabEnum, BusinessDetailTabEnum.PROMOTION_ACTIVITY_APPLICABLE_OBJECTS) &&!Objects.equals(promotionApplicableObjectType, ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode())) {
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    detailTabPojo.setFormId(formId);
                    tabPojoList.add(detailTabPojo);
                }
                break;
            default:
                for (BusinessDetailTabEnum tabEnum : tabEnumList) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(detailTabPojo.getKey());
                    tabPojoList.add(detailTabPojo);
                }
                break;
        }

    }

    public void handelDetailButton(Integer businessType, List<ButtonPojo> buttonPojoList, UserVO loginUser, PaasFormEntityExt paasFormEntityExt, Integer status) {
        List<BusinessDetailButtonEnum> buttonEnumList = BusinessDetailButtonEnum.getByBusinessTypeAndPermission(businessType, loginUser.getPermSet());
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);

        switch (xbbRefTypeEnum){
            case FULL_DISCOUNT_COUPON:
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    //已经下架的不能编辑和删除
                    if (!Objects.equals(status, MarketingStatusEnum.WAIT_ONLINE.getCode()) && (Objects.equals(buttonEnum, BusinessDetailButtonEnum.FULL_DISCOUNT_COUPON_DEL)
                            || Objects.equals(buttonEnum, BusinessDetailButtonEnum.FULL_DISCOUNT_COUPON_EDIT))) {
                        continue;
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojo.setFormId(paasFormEntityExt.getId());
                    buttonPojoList.add(buttonPojo);
                }
                break;
            case SPECIAL_GOODS:
                for (BusinessDetailButtonEnum buttonEnum : buttonEnumList) {
                    //已经下架的不能编辑和删除
                    if (!Objects.equals(status, MarketingStatusEnum.WAIT_ONLINE.getCode()) && (Objects.equals(buttonEnum, BusinessDetailButtonEnum.SPECIAL_GOODS_DEL)
                            || Objects.equals(buttonEnum, BusinessDetailButtonEnum.SPECIAL_GOODS_EDIT))) {
                        continue;
                    }
                    ButtonPojo buttonPojo = new ButtonPojo();
                    SaasButtonEnum saasButtonEnum = buttonEnum.getAnEnum();
                    BeanUtil.copyProperties(saasButtonEnum, buttonPojo);
                    buttonPojo.setLinkBusinessType(buttonEnum.getLinkBusinessType());
                    buttonPojo.setFormId(paasFormEntityExt.getId());
                    buttonPojoList.add(buttonPojo);
                }
                break;
        }
    }

    /**
     * 经销商区域回显
     * @param data
     * @param corpid
     */
    public Map<Long, String> analysisLocation(JSONObject data, String corpid){
        JSONArray location = data.getJSONArray(MarketingActivityManagementEnum.APPLICABLE_LOCATION.getAttr());
        Map<Long, String> areaMap = new HashMap<>();
        List<DistributorAreaEntity> allDistributorArea = distributorAreaModel.findAllDistributorArea(corpid);
        allDistributorArea.forEach(item -> areaMap.put(item.getId(), item.getName()));
        if (Objects.nonNull(location) && !location.isEmpty()) {
            JSONArray areas = new JSONArray();
            for (int i = 0; i < location.size(); i++) {
                Long areaId = location.getLong(i);
                if (areaMap.containsKey(areaId)) {
                    String areaName = areaMap.get(areaId);
                    JSONObject area = new JSONObject();
                    area.put(StringConstant.SAAS_LINK_BUSINESS_ID, areaId);
                    area.put(StringConstant.SAAS_LINK_BUSINESS_NAME, areaName);
                    areas.add(area);
                }
            }
            data.put(MarketingBaseEnum.APPLICABLE_LOCATION.getAttr(), areas);
        }
        return areaMap;
    }

    /**
     * 获取公司所有单位项
     * @param corpid
     * @throws XbbException
     */
    public Map<String, String> getAllUnitItems(String corpid) throws XbbException {
        Map<String, String> unitItemsMap = new HashMap<>();
        List<ItemPoJo> items = new ArrayList<>();

        Boolean multiUnit = companyConfigService.getMultiUnit(corpid);
        if (multiUnit) {
            //开了多单位的公司
            items = saasFormHelp.getProductItems(corpid);
        }else {
            PaasFormExplainEntity productExplains = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
            List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(productExplains.getExplains(), FieldAttrEntity.class);
            for (FieldAttrEntity entity : fieldAttrEntityList) {
                if (Objects.equals(entity.getAttr(), ProductEnum.UNIT.getAttr())) {
                    items = entity.getItems();
                    break;
                }
            }
        }
        items.forEach(item -> unitItemsMap.put(item.getValue().toString(), item.getText()));
        return unitItemsMap;
    }

    /**
     * 优惠券不可用产品解析
     * @param data
     * @param corpid
     * @param detailTabDataGetDTO
     */
    public JSONArray analysisDisableProduct(JSONObject data, String corpid, DetailTabDataGetDTO detailTabDataGetDTO) throws XbbException {
        Map<String, String> unitItemsMap = getAllUnitItems(corpid);
        JSONArray inapplicableProduct = data.getJSONArray(MarketingBaseEnum.INAPPLICABLE_PRODUCT.getAttr());
        List<Long> productIds = new ArrayList<>();
        for (int i = 0; i < inapplicableProduct.size(); i++) {
            Long productId = inapplicableProduct.getLong(i);
            productIds.add(productId);
        }
        if (Objects.nonNull(detailTabDataGetDTO)) {
            detailTabDataGetDTO.setTotal(productIds.size());
            Integer pageSize = detailTabDataGetDTO.getPageSize();
            Integer page = detailTabDataGetDTO.getPage();
            Integer sumPage = page * pageSize;
            if (sumPage > productIds.size()) {
                sumPage = productIds.size();
            }
            productIds = productIds.subList((page - 1) * pageSize, sumPage);
        }
        List<PaasFormDataEntityExt> productsByIds = productModel.getProductsByIds(corpid, productIds, DelEnum.NORMAL.getDel(), null, null);
        productService.setChildSpecification(productsByIds, corpid);
        JSONArray resultArray = new JSONArray();
        for (PaasFormDataEntityExt productEntityExt : productsByIds) {
            JSONObject productEntityExtData = productEntityExt.getData();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, productEntityExt.getId());
            jsonObject.put(ProductEnum.NAME.getAttr(), productEntityExtData.getString(ProductEnum.NAME.getAttr()));
            jsonObject.put(ProductEnum.SERIALNO.getAttr(), productEntityExt.getSerialNo());
            jsonObject.put(ProductEnum.SPECIFICATION.getAttr(), productEntityExtData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
            jsonObject.put(ProductEnum.UNIT.getAttr(), unitItemsMap.getOrDefault(productEntityExtData.getString(ProductEnum.UNIT.getAttr()), ""));
            resultArray.add(jsonObject);
        }
        return resultArray;
    }

    /**
     * 具体经销商解析
     * @param data
     * @param corpid
     * @param detailTabDataGetDTO
     */
    public JSONArray analysisDistributor(JSONObject data, String corpid, List<ItemPoJo> distributorLevel, Map<Long, String> distributorAreaMap, DetailTabDataGetDTO detailTabDataGetDTO) throws XbbException {
        //具体经销商需要解析
        JSONArray distributors = data.getJSONArray(MarketingBaseEnum.DISTRIBUTOR.getAttr());
        List<Long> distributorIds = new ArrayList<>();
        for (int i = 0; i < distributors.size(); i++) {
            Long distributorId = distributors.getLong(i);
            distributorIds.add(distributorId);
        }
        if (Objects.nonNull(detailTabDataGetDTO)) {
            Integer pageSize = detailTabDataGetDTO.getPageSize();
            Integer page = detailTabDataGetDTO.getPage();
            Integer sumPage = page * pageSize;
            if (sumPage > distributorIds.size()) {
                sumPage = distributorIds.size();
            }
            distributorIds = distributorIds.subList((page - 1) * pageSize, sumPage);
        }
        List<CustomerEntityExt> customerEntityExts = customerModel.getByKeys(distributorIds, corpid);

        List<String> userIds = new ArrayList<>();
        for (CustomerEntityExt customerEntityExt : customerEntityExts) {
            userIds.add(customerEntityExt.getOwnerId());
        }
        Map<String, String> scaleItemsMap = new HashMap<>();
        distributorLevel.forEach(item -> scaleItemsMap.put(item.getValue().toString(),item.getText()));
        Map<String, String> userNameMapping = userModel.getUserNameMap(corpid, userIds);
        JSONArray distributorArray = new JSONArray();
        for (CustomerEntityExt customerEntityExt : customerEntityExts) {
            JSONObject customerEntityExtData = customerEntityExt.getData();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(StringConstant.SAAS_LINK_BUSINESS_ID, customerEntityExt.getId());
            jsonObject.put(DistributorEnum.NAME.getSaasAttr(), customerEntityExtData.getString(DistributorEnum.NAME.getAttr()));
            jsonObject.put(DistributorEnum.AREA.getSaasAttr(), distributorAreaMap.getOrDefault(customerEntityExtData.getLong(DistributorEnum.AREA.getAttr()), ""));
            jsonObject.put(DistributorEnum.SCALE.getSaasAttr(), scaleItemsMap.getOrDefault(customerEntityExtData.getString(DistributorEnum.SCALE.getAttr()), ""));
            jsonObject.put(DistributorEnum.OWNER_ID.getSaasAttr(), userNameMapping.getOrDefault(customerEntityExt.getOwnerId(), ""));
            distributorArray.add(jsonObject);
        }
        return distributorArray;
    }


    /**
     * 活动名称解析
     * @param name
     * @param corpid
     */
    public String analysisCouponName(String name, String corpid, Integer businessType){
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        String alias = xbbRefTypeEnum.getName();
        if (name.length() > alias.length()) {
            name = name.substring(0, name.length() - alias.length());
        }
        return name;
    }

    public List<TopPermissionsPoJo> handelMobileWorkFlow(Integer businessType, UserVO loginUser, Integer status, Integer subBusinessType, String corpid) {
        List<WorkFlowEnum> workFlowEnumList = WorkFlowEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, loginUser.getPermSet());
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(subBusinessType, corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        List<TopPermissionsPoJo> topPermissions = new ArrayList<>();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case FULL_DISCOUNT_COUPON:
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(workFlowEnum.getAttr(), WorkFlowEnum.FULL_DISCOUNT_COUPON_ONLINE.getAttr()) && !Objects.equals(status, MarketingStatusEnum.WAIT_ONLINE.getCode())) {
                        continue;
                    }
                    if (Objects.equals(workFlowEnum.getAttr(), WorkFlowEnum.FULL_DISCOUNT_COUPON_OFFLINE.getAttr()) && !Objects.equals(status, MarketingStatusEnum.ONLINE.getCode())) {
                        continue;
                    }
                    //已经下架的不能编辑和删除
                    if (!Objects.equals(status, MarketingStatusEnum.WAIT_ONLINE.getCode()) && (Objects.equals(workFlowEnum, WorkFlowEnum.FULL_DISCOUNT_COUPON_DEL)
                            || Objects.equals(workFlowEnum, WorkFlowEnum.FULL_DISCOUNT_COUPON_EDIT))) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setFormId(paasFormEntityExt.getId());
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
            case SPECIAL_GOODS:
                for (WorkFlowEnum workFlowEnum : workFlowEnumList) {
                    if (Objects.equals(workFlowEnum.getAttr(), WorkFlowEnum.SPECIAL_GOODS_ONLINE.getAttr()) && !Objects.equals(status, MarketingStatusEnum.WAIT_ONLINE.getCode())) {
                        continue;
                    }
                    if (Objects.equals(workFlowEnum.getAttr(), WorkFlowEnum.SPECIAL_GOODS_OFFLINE.getAttr()) && !Objects.equals(status, MarketingStatusEnum.ONLINE.getCode())) {
                        continue;
                    }
                    //已经下架的不能编辑和删除
                    if (!Objects.equals(status, MarketingStatusEnum.WAIT_ONLINE.getCode()) && (Objects.equals(workFlowEnum, WorkFlowEnum.SPECIAL_GOODS_EDIT)
                            || Objects.equals(workFlowEnum, WorkFlowEnum.SPECIAL_GOODS_DEL))) {
                        continue;
                    }
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(workFlowEnum, topPermissionsPoJo);
                    topPermissionsPoJo.setFormId(paasFormEntityExt.getId());
                    topPermissions.add(topPermissionsPoJo);
                }
                break;
        }
        return topPermissions;
    }

    public JSONArray analysisPromotionProduct(PaasFormDataEntityExt paasFormDataEntityExt, String corpid, DetailTabDataGetDTO detailTabDataGetDTO) throws XbbException {
        Long id = paasFormDataEntityExt.getId();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("refId", id);
        param.put("del", 0);
        Integer entityCount = promotionProductModel.getEntityCount(param);
        if (Objects.nonNull(detailTabDataGetDTO)) {
            param.put("start", (long)(detailTabDataGetDTO.getPage() - 1) * detailTabDataGetDTO.getPageSize());
            param.put("pageSize", detailTabDataGetDTO.getPageSize());
        }

        List<PromotionProductEntity> promotionProductEntityList = promotionProductModel.findEntities(param);
        if (Objects.nonNull(detailTabDataGetDTO)) {
            detailTabDataGetDTO.setTotal(entityCount);
        }
        List<Long> productIds = new ArrayList<>();
        for (PromotionProductEntity promotionProductEntity : promotionProductEntityList) {
            productIds.add(promotionProductEntity.getProductId());
        }
        Map<Long, PaasFormDataEntityExt> productSaveMap = marketingProductSaveMap(corpid, productIds);

        JSONArray productArray = new JSONArray();
        for (PromotionProductEntity promotionProductEntity : promotionProductEntityList) {
            JSONObject data = promotionProductEntity.getData();
            Long productId = promotionProductEntity.getProductId();
            if (productSaveMap.containsKey(productId)) {
                PaasFormDataEntityExt originProduct = productSaveMap.get(productId);
                data.put(ProductEnum.NAME.getAttr(), originProduct.getData().getString(ProductEnum.NAME.getAttr()));
                data.put(ProductEnum.SPECIFICATION.getAttr(), originProduct.getData().getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()));
                productArray.add(data);
            }
        }

        return productArray;
    }



    /**
     * 用户关联产品保存
     * @param corpid
     * @return
     * @throws XbbException
     */
    public Map<Long,PaasFormDataEntityExt> marketingProductSaveMap(String corpid, List<Long> productIdList) throws XbbException {
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),productIdList));
        List<PaasFormDataEntityExt> childList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT,boolQueryBuilder,PaasFormDataEntityExt.class,null);
        productService.setChildSpecification(childList, corpid);
        Map<Long, PaasFormDataEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntityExt entityExt : childList) {
            JSONObject data = entityExt.getData();
            data.put(ProductEnum.PRODUCT_NO.getAttr(),entityExt.getSerialNo());
            productMap.put(entityExt.getDataId(),entityExt);
        }
        return productMap;
    }

    /**
     * 拿到在促销的父产品
     * @param corpid
     * @return
     * @throws XbbException
     */
    public HashSet<Long> getPromotionProduct(String corpid) throws XbbException {
        List<PaasFormDataEntityExt> activityList = queryOnlineActivity(corpid, -1L);
        if (CollectionUtils.isEmpty(activityList)) {
            return new HashSet<>();
        }
        List<Long> activityIdList = new ArrayList<>();
        activityList.forEach(item -> activityIdList.add(item.getDataId()));
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID, corpid);
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        params.put("refIdIn", activityIdList);
        params.put("groupByStr", ParameterConstant.PARENT_COLUMN_ID);
        params.put(ParameterConstant.COLUMNS, ParameterConstant.PARENT_COLUMN_ID);
        List<PromotionProductEntity> entities = promotionProductModel.findEntities(params);
        HashSet<Long> parentIdSet = new HashSet<>();
        entities.forEach(item -> parentIdSet.add(item.getParentId()));
        return parentIdSet;
    }



    /**
     * 查询是否有该经销商适用的活动
     * @param
     * @return
     */
    public List<PaasFormDataEntityExt> queryOnlineActivity(String corpid, Long distributorId) throws XbbException {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        //解析查询条件
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(MarketingBaseEnum.getAttrConnectData(MarketingBaseEnum.STATUS), MarketingStatusEnum.ONLINE.getCode()));
        boolQueryBuilder.filter(rangeQuery(MarketingBaseEnum.getAttrConnectData(MarketingBaseEnum.BEGIN_TIME)).lte(DateTimeUtil.getTodayInt()));
        boolQueryBuilder.filter(rangeQuery(MarketingBaseEnum.getAttrConnectData(MarketingBaseEnum.END_TIME)).gte(DateTimeUtil.getTodayInt()));
        if (Objects.nonNull(distributorId) && distributorId != -1) {
            CustomerEntityExt customerEntityExt = customerModel.getByKey(distributorId, corpid);
            //拿到经销商级别
            String level = customerEntityExt.getData().getString(DistributorEnum.SCALE.getAttr());
            Long area = customerEntityExt.getData().getLong(DistributorEnum.AREA.getAttr());
            BoolQueryBuilder allAreaShouldBuilder = boolQuery().mustNot(existsQuery(MarketingBaseEnum.APPLICABLE_LOCATION.getAttr()));
            BoolQueryBuilder specificAreaShouldBuilder = boolQuery().filter(termsQuery(MarketingBaseEnum.getAttrConnectData(MarketingBaseEnum.APPLICABLE_LOCATION), Arrays.asList(area)));

            BoolQueryBuilder shouldBuilder = boolQuery();
            shouldBuilder.filter(termQuery(MarketingBaseEnum.getAttrConnectData(MarketingBaseEnum.APPLICABLE_OBJECT_TYPE), ApplicableObjectTypeEnum.ALL.getCode()));
            shouldBuilder.should(specificAreaShouldBuilder).should(allAreaShouldBuilder).minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
            boolQueryBuilder.should(shouldBuilder);
            shouldBuilder = boolQuery();
            shouldBuilder.filter(termQuery(MarketingBaseEnum.getAttrConnectData(MarketingBaseEnum.APPLICABLE_OBJECT_TYPE), ApplicableObjectTypeEnum.DISTRIBUTOR_LEVEL.getCode()));
            shouldBuilder.filter(termsQuery(MarketingBaseEnum.getAttrConnectData(MarketingBaseEnum.DISTRIBUTOR_LEVEL), Arrays.asList(level)));
            shouldBuilder.should(specificAreaShouldBuilder).should(allAreaShouldBuilder).minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
            boolQueryBuilder.should(shouldBuilder);
            shouldBuilder = boolQuery();
            shouldBuilder.filter(termQuery(MarketingBaseEnum.getAttrConnectData(MarketingBaseEnum.APPLICABLE_OBJECT_TYPE), ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode()));
            shouldBuilder.filter(termsQuery(MarketingBaseEnum.getAttrConnectData(MarketingBaseEnum.DISTRIBUTOR),  Arrays.asList(distributorId)));
            shouldBuilder.should(specificAreaShouldBuilder).should(allAreaShouldBuilder).minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
            boolQueryBuilder.should(shouldBuilder);
            boolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
        }
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PROMOTION_ACTIVITY_MANAGEMENT.getIndex());
        sourceBuilder.query(boolQueryBuilder);
        sourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.ASC));
        List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias());
        EsUtil.setFieldList(sourceBuilder, fieldList);
        searchRequest.source(sourceBuilder);
        PageRequest pageRequest= EsUtil.setPage(sourceBuilder, 1, 50);
        XbbAggregatedPage<PaasFormDataEntityExt> xbbAggregatedPage = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
        List<PaasFormDataEntityExt> content = xbbAggregatedPage.getContent();
        return content;
    }
    /**
     * 拿到在促销的子产品
     * @param corpid
     * @return
     * @throws XbbException
     */
    public HashSet<Long> getChildPromotionProduct(Long parentId, String corpid) throws XbbException {
        List<PaasFormDataEntityExt> activityList = queryOnlineActivity(corpid, -1L);
        if (CollectionUtils.isEmpty(activityList)) {
            return new HashSet<>();
        }
        List<Long> activityIdList = new ArrayList<>();
        activityList.forEach(item -> activityIdList.add(item.getDataId()));
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID, corpid);
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        params.put("refIdIn", activityIdList);
        params.put(ParameterConstant.PARENT_ID, parentId);
        params.put(ParameterConstant.COLUMNS,  "product_id");
        List<PromotionProductEntity> entities = promotionProductModel.findEntities(params);
        HashSet<Long> childIdSet = new HashSet<>();
        entities.forEach(item -> childIdSet.add(item.getProductId()));
        return childIdSet;
    }

    public List<String> getPushUserIds(JSONObject data, String corpid) throws XbbException {
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        String applicableObjectType = data.getString(MarketingBaseEnum.APPLICABLE_OBJECT_TYPE.getAttr());
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = boolQuery();
        queryBuilder.filter(termQuery("corpid.keyword", corpid));
        queryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        queryBuilder.filter(termQuery(ParameterConstant.FORMID, paasFormEntityExt.getId()));
        if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.SPECIFIC_DISTRIBUTOR.getCode())) {
            queryBuilder.filter(termsQuery(StringConstant.DATA_ID, data.getJSONArray(MarketingBaseEnum.DISTRIBUTOR.getAttr())));
        }else if (Objects.equals(applicableObjectType, ApplicableObjectTypeEnum.DISTRIBUTOR_LEVEL.getCode())){
            queryBuilder.filter(termsQuery(DistributorEnum.getAttrConnectData(DistributorEnum.SCALE), data.getJSONArray(MarketingBaseEnum.DISTRIBUTOR_LEVEL.getAttr())));
        }
        if (!CollectionUtils.isEmpty(data.getJSONArray(MarketingBaseEnum.APPLICABLE_LOCATION.getAttr()))) {
            queryBuilder.filter(termsQuery(DistributorEnum.getAttrConnectData(DistributorEnum.AREA), data.getJSONArray(MarketingBaseEnum.APPLICABLE_LOCATION.getAttr())));
        }
        IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        queryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, customerIndex.getType()));
        searchSourceBuilder.query(queryBuilder);
        List<String> fieldList = new ArrayList<>();
        fieldList.add(FieldTypeEnum.DATAID.getAlias());
        List<PaasFormDataEntityExt> entityExts = paasEsModel.list(searchSourceBuilder, customerIndex, fieldList, 1, EsNormalConstant.FIND_NUM);
        List<Long> distributorIds = new ArrayList<>();
        entityExts.forEach(item -> distributorIds.add(item.getDataId()));
        List<DistributorAccountEntity> users = distributorAccountModel.getByDistributorIdIn(corpid, distributorIds);
        List<String> userIds = new ArrayList<>();
        users.forEach(item -> userIds.add(item.getId().toString()));

        return userIds;
    }
}
